package com.pwc.conversionTool.biz.sendSoap;

import static com.pwc.GAE.blobstore.BlobstoreUtil.getBlobInfo;
import static com.pwc.GAE.blobstore.BlobstoreUtil.getBlobstoreInputStream;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.google.appengine.api.blobstore.BlobInfo;
import com.pwc.conversionTool.dao.DataAdaptorDao;
import com.pwc.conversionTool.dataAdaptor.CsvUtil;
import com.pwc.conversionTool.dataAdaptor.DataAdaptor;
import com.pwc.conversionTool.dataAdaptor.IDataAdaptor;
import com.pwc.conversionTool.entity.CsvDataType;
import com.pwc.conversionTool.entity.DataTemplate;
import com.pwc.conversionTool.entity.Operation;
import com.pwc.conversionTool.entity.TaskLog;

public abstract class BaseProcess implements IDataAdaptorProcess {
	
	
	protected DataAdaptorDao dataAdaptorDao = new DataAdaptorDao();

	protected TaskLog taskLog = null;

	protected Operation operation=null;
	
	protected List<String> keys=null;
	
	protected IDataAdaptor adaptorUtil=null;
	
	protected DataTemplate dataTemplate = null;
	
	protected DataAdaptor dataAdaptor = new DataAdaptor();
	
	protected InputStream in =null;
	
	protected BlobInfo info=null;
	
	public BaseProcess(TaskLog taskLog,Operation operation, List<String> keys)
	{
		this.taskLog=taskLog;
		this.operation=operation;
		this.keys=keys;
		dataTemplate = operation.getDataAdaptorData();
	}
	
	
	
	@Override
	public List<IDataAdaptor> getDataAdaptors() throws IOException {
		List<IDataAdaptor> dataAdaptors = new ArrayList<IDataAdaptor>();
		for (String key : keys) {
			in = getBlobstoreInputStream(key);
			info=getBlobInfo(key);
			initialUtil();
			if (Arrays.equals(dataTemplate.getHeader(), adaptorUtil.getHeader())) {
				dataAdaptor.setHeader(adaptorUtil.getHeader());
				dataAdaptor.setContent(adaptorUtil.getContent());
				dataAdaptors.add(dataAdaptor);
				taskLog.addMessage("header matchs file:"+getBlobInfo(key).getFilename());
			} else {
				taskLog.addMessage("header is not match in getting csv file:"+getBlobInfo(key).getFilename());
				taskLog.setHasError(true);
				return null;
			}

		}

		return dataAdaptors;
	}
	
	/**
	 * base for csv type
	 * @throws IOException
	 */
	public void initialUtil() throws IOException
	{
		
		CsvDataType csvDataType = dataAdaptorDao.getCsvDataTypeByDataTemplate(dataTemplate);

		String columnSepatator = csvDataType.getColumnSepatator();

		String lineSeparator = csvDataType.getLineSeparator();

		if (lineSeparator != null && !lineSeparator.isEmpty() && columnSepatator != null && !columnSepatator.isEmpty()) {
			adaptorUtil = new CsvUtil(in, lineSeparator.charAt(0), columnSepatator.charAt(0));
		} else {
			adaptorUtil = new CsvUtil(in);
		}
	}
	
	
}
